(function($){
	debug = false;
	
	$.gInit = function(url)
	{
		if(debug) console.log('Gadgets Init');
		gadgets = {'url': url, gadget : []};
		gadgets.gadget['names'] = new Array;
		var gg = $('.gadget');
		$.each(gg, function(i,v)
		{
			var name = $(v).attr('id');
			gadgets.gadget.names[i] = name;
			gadgets.gadget[name] = new Array;
			gadgets.gadget[name].element = $(v);
			$.post(url+'gadget/gload/'+$(v).attr('id'),
				{'param' : name},
				function(res)
				{
					gadgets.gadget[name].data = res;
					$(v).html(res);
				}, 'html');
		});
	}

	$.gListern = function(name, ev, func)
	{
		if(name == '') return false;
		else
		{
			if(debug) console.log('Add event "'+ev+'" listener to: '+name);
			$('#'+name).delegate('', ev, func);
		}
	}

	$.gEmit = function(ev, param)
	{
		if(debug)
		{
			console.log('Event: '+ev);
			console.log(gadgets.gadget);
		}
		$.each(gadgets.gadget.names, function(i,e){
			gadgets.gadget[e].element.trigger(ev, param);
		});
	}

	$.gIsSet = function(name)
	{
		if(debug) console.log('GadgetIsSet');
		if(undefined !== gadgets.gadget[name])
		{
			if(debug) console.log('Gadget '+name+' Set');
			return true;
		}
		else return false;
	}

	$.gLoad = function(name, container, callback)
	{
		if($.gIsSet(name))
			$.gShow(name);
		else
		{
			if(debug) console.log('Gadget Load: '+name);
			gadgets.gadget.names[gadgets.gadget.names.length] = name;
			gadgets.gadget[name] = new Array;
			gadgets.gadget[name].element = container;
			$.post(gadgets.url+'gadget/gload/'+name,
				{'param' : $(container).attr('id')},
				function(res)
				{
					gadgets.gadget[name].data = res;
					container.html(res);
					if(callback !== undefined)
						callback(gadgets.gadget[name]);
				}, 'html');
		}
	}
	
	$.gDel = function(name, callback)
	{
		if(gadgets.gadget[name] !== undefined)
		{
			if(debug) console.log('Gadget Delete: '+name);
			gadgets.gadget[name].element.html('');
			delete gadgets.gadget[name];
			$.each(gadgets.gadget.names, function(i,e){
				if(e == name)
				{
					delete gadgets.gadget.names[i];
					gadgets.gadget.names.length--;
				}
			});
			if(callback !== undefined)
				callback();
		}
	}

	$.gReload = function(name, callback)
	{
		if($.gIsSet(name))
		{
			if(debug) console.log('Gadget Reload: '+name);
			var container = gadgets.gadget[name].element;
			$.post(gadgets.url+'gadget/gload/'+name,
				{'param' : container.attr('id')},
				function(res)
				{
					gadgets.gadget[name].data = res;
					container.html(res);
					if(callback !== undefined)
						callback(gadgets.gadget[name]);
				}, 'html');
		}
		else return false;
	}

	$.gShow = function(name, callback)
	{
		if(gadgets.gadget[name] !== undefined)
		{
			if(debug) console.log('Gadget Show: '+name);
			gadgets.gadget[name].element.html(gadgets.gadget[name].data);
			if(callback !== undefined) callback(gadgets.gadget[name].element);
		}
	}

})(jQuery)
